<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>聊天界面</title>
    <link rel="stylesheet" href="./css/common.css">

    <!-- 表情 -->

    <link rel="stylesheet" href="lib/css/jquery.mCustomScrollbar.min.css" />
    <link rel="stylesheet" href="dist/css/jquery.emoji.css" />


</head>
<style>
    .client-container {
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .main {
        width: 785px;
        height: 570px;
        background-color: rgb(245, 245, 245);
        border-radius: 5px;

        display: flex;

        z-index: 0;

    }

    .main .left {
        width: 180px;
        height: 100%;
        background-color: rgba(46, 46, 46, 0.802);

        border-top-left-radius: 5px;
        border-bottom-left-radius: 5px;
    }

    .main .right {
        width: 605px;
        height: 100%;
        padding: 0 10px;
    }


    /* 背景 */
    .beijing {
        width: 100%;
        height: 100%;

        /* 背景图 */
        background-image: url(./img/bg.jpg);
        background-repeat: no-repeat;
        background-position: center center;
        background-size: cover;

        /* 背景图重叠 */
        position: absolute;
        /* 定位 */
        top: 0;
        left: 0;

        /* 设置z轴坐标 */
        z-index: -22;

        /* 虚化背景 */
        /* 滤镜只能加到div上 */
        filter: blur(1px);
        filter: brightness(30%)
    }

    .user {

        height: 50px;
        /* 文字 */
        font-size: 16px;
        font-family: "微软雅黑";
        font-weight: bold;
        /* 文字垂直居中显示,行高和高度一样 */
        line-height: 57px;
        color: #ffffff;
        padding: 0 20px;

    }

    .main .left .search {
        height: 40px;
        padding: 0 10px;

        /*  让元素水平排列 */
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .main .left .search input {
        height: 32px;
        width: 115px;
        line-height: 34px;
        font-size: 14px;
        color: #ffffff;
        background-color: rgb(23, 23, 23);

        /* 去除边框.轮廓线 */
        border: none;
        outline: none;
        /* 框内文字不定格 */
        padding-left: 5px;

        border-top-left-radius: 5px;
        border-bottom-left-radius: 5px;
    }

    .main .left .search button:active {
        background-color: #ffffff;
    }

    .main .left .search button {
        height: 32px;
        width: 30px;
        border: none;
        outline: none;

        border-top-right-radius: 5px;
        border-bottom-right-radius: 5px;
        background-color: rgb(23, 23, 23);

        background-image: url(./img/搜索.png);
        background-repeat: no-repeat;
        background-size: 16px 16px;
        background-position: center center;
    }

    .main .left .tab {
        height: 40px;
        /* 水平排列 */
        display: flex;
        /* 居中 */
        align-items: center;
        border-bottom: 1px #000;
    }

    .main .left .tab .tab-session {
        height: 80%;
        width: 33%;

        background-image: url(./img/会话1.png);
        background-repeat: no-repeat;
        background-size: 25px;
        background-position: center center;
    }

    .main .left .tab .tab-friend {
        height: 80%;
        width: 33%;

        background-image: url(./img/好友1.png);
        background-repeat: no-repeat;
        background-size: 25px;
        background-position: center center;
    }

    .main .left .tab .tab-find-friend {
        height: 80%;
        width: 33%;

        background-image: url(./img/好友申请.png);
        background-repeat: no-repeat;
        background-size: 30px;
        background-position: center center;
    }

    .main .left .list {
        height: 400px;

        /* 如果里面内容过多,提供滚轮查看 */
        overflow: auto;
    }

    .main .left .list li {
        height: 50px;
        padding: 10px 20px;
        color: #fffcfc;

        border-bottom: 1px solid #3a3a58;
    }

    .main .left .list .selected {
        background-color: rgb(86, 114, 157);
    }

    /* 会话列表 */
    .main .left .list li h3 {
        font-weight: normal;
        margin-top: -3px;
        margin-bottom: 3px;
        height: 10px;
        font-size: 15px;
        line-height: 20px;
    }


    .main .left .list li p {
        height: 10px;
        font-size: 12px;
        line-height: 28px;
    }

    /* 隐藏属性 */
    .hide {
        display: none;
    }

    /* 隐藏滚动条 */
    ::-webkit-scrollbar {
        display: none;
    }

    #h3 {
        margin-top: -3px;
        margin-bottom: 3px;
        height: 10px;
        font-size: 14px;
        line-height: 20px;
    }

    #find-friend-list h2 {
        height: 50px;
        /* 文字 */
        font-size: 15px;
        font-weight: bold;
        /* 文字垂直居中显示,行高和高度一样 */
        line-height: 57px;
        color: #10a31c;
        padding: 0 20px;
    }

    .right.beg {
        display: block;
        background-color: #0056b3;
        margin-top: 90px;
    }

    .main .right .title {
        height: 50px;
        line-height: 50px;
        font-size: 18px;
        border-bottom: 1px solid rgb(27, 28, 29);
    }

    .main .right .title p {
        margin-left: 10px;
    }

    .main .right .title button {

        margin-top: -30px;
        padding: 4px 10px;
        font-weight: bold;
        float: right;
        background-color: rgb(245, 245, 245);
        border: none;
    }

    .main .right .title button:active {
        background-color: rgb(175, 179, 183);
    }

    .main .right .message-show {
        height: 360px;
        padding: 10px;
        border-bottom: 1px solid #8c8a8a;
        /* 滚动条 */
        overflow: auto;
    }

    .main .right .message-show2 {
        height: 520px;
        padding: 10px;
        /* 滚动条 */
        overflow: auto;
    }

    .main .right .message-show3 {
        height: 520px;
        padding: 10px;
        /* 滚动条 */
        overflow: auto;
    }

    /* .main .right.message-show h4 {
        display: block;
    } */

    .main .right .message-show {
        display: flex;
        flex-direction: column;
    }

    .main .right .message-show .message,
    .main .right .message-show .message .box h4,
    .main .right .message-show .message .box p {

        margin-top: 3px;
        font-weight: normal;
        /* 宽度默认100%,高度不设定 */
        /* display: flex; */
    }


    /* 子元素靠左 */
    /* .main .right .message-show .message-left .box {
        justify-self: flex-start;
    } */

    /* 子元素靠右 */
    .main .right .message-show .message-right .box {
        float: right;
    }

    .main .right .message-show .message-right,
    .main .right .message-show .message-right h4,
    .main .right .message-show .message-right p {
        float: right;

    }


    .box {
        max-width: 300px;
        flex-direction: column;
        display: flex;
        /* justify-content: space-between; */
    }


    .main .right .message-show .box p {
        word-wrap: break-word;
        /* 四边边距 */
        width: 250px;
        padding: 10px;
        border-radius: 5px;
    }

    /* .main .right .message-show .box p {
        width: auto;
    } */

    /* 消息旗袍 */
    .main .right .message-show .message-left .box p {
        background-color: rgb(255, 255, 255);
        word-wrap: break-word;
    }

    .main .right .message-show .message-right .box h4 {
        float: right;
    }

    .main .right .message-show .message-right .box p {
        background-color: rgb(149, 236, 106);
        word-wrap: break-word;
    }

    .close {
        border: none;
        margin-top: 1px;
        padding: 5px 5px;
        font-weight: bold;
        float: right;
        /* display: flex; */
        background-color: rgb(245, 245, 245);
    }

    .close:active {
        background-color: rgb(251, 115, 115);
    }

    .function button {
        font-size: 20px 20px;
        padding: 10px 10px;
        font-weight: bold;
        background-color: rgb(245, 245, 245);
        border: none;
        margin-right: 5px;
    }

    .function .a {
        background-image: url(./img/表情新.png);
        background-repeat: no-repeat;
        background-size: 20px 20px;
    }

    .function .b {
        background-image: url(./img/图片.png);
        background-repeat: no-repeat;
        background-size: 20px 20px;
    }

    .function .c {
        background-image: url(./img/截屏.png);
        background-repeat: no-repeat;
        background-size: 20px 20px;
    }

    .function button:active {
        background-color: rgb(175, 179, 183);
    }

    /* 弹框的样式 */
    #fileUploadPopup {
        display: none;
        position: fixed;
        z-index: 9999;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        overflow: auto;
        background-color: rgba(0, 0, 0, 0.5);
    }

    /* 弹框内容的样式 */
    #fileUploadPopupContent {
        background-color: #fff;
        margin: 15% auto;
        padding: 20px;
        border-radius: 10px;
        width: 400px;
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        overflow: auto;
    }

    /* 关闭按钮的样式 */
    .close2 {

        color: #aaa;
        float: right;
        font-size: 28px;
        font-weight: bold;
        cursor: pointer;
        transition: 0.3s;
    }

    .close2:hover,
    .close2:focus {
        color: black;
        text-decoration: none;
        cursor: pointer;
    }

    /* 表单样式 */
    #fileUploadForm {
        margin-bottom: 20px;
    }

    /* 文件输入和按钮的样式 */
    #fileInput {
        display: block;
        margin-bottom: 10px;
    }

    .file-upload-btn {
        display: inline-block;
        padding: 10px 20px;
        background-color: #000000;
        color: #fff;
        border-radius: 5px;
        border: none;
        cursor: pointer;
        transition: 0.3s;
    }

    .file-upload-btn:hover {
        background-color: #4f5271;
    }

    .cancel-btn {
        display: inline-block;
        padding: 10px 20px;
        background-color: #e9ecef;
        color: #333;
        border-radius: 5px;
        border: none;
        cursor: pointer;
        transition: 0.3s;
    }

    .cancel-btn:hover {
        background-color: #ddd;
    }

    #messageInput {

        width: 100%;
        height: 100px;
        border: none;
        overflow: auto;
    }

    /* #fileInput {
        display: none;
    } */

    #send {
        float: right;
        padding: 1px 1px;
        width: 60px;
        height: 28px;
    }

    .right .content .text {
        height: 40px;
        width: 400px;
    }

    .right .content,
    .right .content .box2 h3 {
        margin-top: 3px;
        font-weight: normal;
        /* 宽度默认100%,高度不设定 */
        display: flex;
    }

    .right .content {
        margin-top: 30px;
        justify-content: center;
        align-items: center;
        border-bottom: 1px solid rgb(27, 28, 29);
    }

    .right .content .box2 button {
        float: right;
        padding: 3px 4px;
        border: none;
        margin-right: 2px;
        background-color: rgb(26, 173, 25);
        color: #ffffff;
    }

    .right .content .box2 button:active {
        background-color: #cfcccc;
    }

    .right .beg {

        margin-top: 210px;
        display: flex;
        justify-content: center;
        align-items: center;
        /* border-bottom: 1px solid rgb(27, 28, 29); */
    }

    .right img {
        width: 115px;
    }


    /* 弹窗 */
    .overlay {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
        z-index: 1000;
    }

    .overlay .modal {
        width: 250px;
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background-color: #fff;
        padding: 20px;
        border-radius: 10px;
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        z-index: 1001;
    }

    .modal input {

        display: block;
        margin-top: 20px;
        margin-bottom: 10px;
        padding: 5px;
        width: 220px;
        border: 1px solid #ccc;
        border-radius: 3px;
    }

    .modal button {
        padding: 8px 12px;
        background-color: #000000;
        color: #fff;
        border: none;
        border-radius: 3px;
        cursor: pointer;
        margin-right: 10px;
    }

    .modal button:hover {
        background-color: #526170;
    }

    .overlay .modal .close-button {
        position: absolute;
        top: 10px;
        right: 10px;
        font-size: 16px;
        cursor: pointer;
    }

    #preview {
        width: 200px;
        height: 200px;
        border: 1px solid #ccc;
        background-size: cover;
        background-position: center;
    }
</style>

<body>
    <div class="beijing"></div>

    <div class="client-container">
        <div class="main">
            <div class="left">
                <div class="user">

                </div>

                <!-- 这是搜索框 -->
                <div class="search">
                    <!-- 输入框 -->
                    <input type="text" placeholder="查找用户">
                    <!-- 按钮,点击按钮搜所 -->
                    <button class="but"></button>
                </div>
                <!-- 标签页 -->
                <div class="tab">
                    <!-- 标签页 -->

                    <!-- 会话标签 -->
                    <div class="tab-session"></div>
                    <!-- 好友标签 -->
                    <div class="tab-friend"></div>
                    <!-- 发现好友 -->
                    <div class="tab-find-friend"></div>
                </div>

                <hr size="1px" color="17000" />

                <!-- 会话列表 -->
                <ul class="list" id="session-list">
                    <!-- <li>
                        <h3>李四</h3>
                        <p>晚上吃啥</p>
                    </li>
                    <li class="selected">
                        <h3>王五</h3>
                        <p>晚上吃啥</p>
                    </li> -->
                </ul>
                <!-- 好友列表 -->
                <ul class="list hide" id="friend-list">
                    
                </ul>
                <!-- 好友申请列表 -->
                <ul class="list hide" id="find-friend-list">
                    <div>
                        <h2>新的好友申请</h2>
                    </div>
                </ul>
            </div>

            <div class="right ">
                <button class="close"> X </button>
                <div class="title">
                    <p>(未选择好友)</p>
                    <button onclick="moreFuc()">...</button>
                </div>
                <!-- 消息区 -->
                <div class="message-show">
                   
                </div>
                <!-- 功能区 -->
                <div class="function">
                    <button id="a" class="a"></button>


                    <button id="customButton" onclick="showFileUploadPopup()" class="b"></button>


                </div>
                <div id="fileUploadPopup" class="overlay">
                    <div id="fileUploadPopupContent" class="popup">
                        <span class="close2" onclick="closeFileUploadPopup()">&times;</span>
                        <iframe class="upload" frameborder="0" name="upload" style="display: none;"></iframe>
                        <form id="fileUploadForm" target="upload" action="/upload" method="post"
                            enctype="multipart/form-data" onsubmit="submitFile(event)">
                            <input type="file" id="fileInput" name="file" accept="image/*" required>
                            <button type="submit" class="file-upload-btn">提交</button>
                            <button type="button" class="cancel-btn" onclick="closeFileUploadPopup()">取消</button>
                        </form>
                    </div>
                </div>

                <!-- 输入框 -->
                <div id="messageInput" contenteditable="true"></div>
                <button id="send" type="submit">发送</button>

            </div>
            <div class="right hide">
                <button class="close"> X </button>
                <div class="title">
                    <p>好友申请</p>

                </div>
                <div class="message-show3">
                    <div class="content">
                        <div class="box2">
                            <h3 class="text">李佳俊</h3>
                            <p>申请理由:</p>
                            <p class="text">我是你的小学同学 <button class="agree">同意</button>
                                <button class="disagree">拒绝</button>
                            </p>
                        </div>
                    </div>
                </div>


            </div>
            <!-- 查找用户 -->
            <div class="right hide">
                <button class="close">X</button>
                <div class="title">
                    <p>用户列表</p>
                </div>
                <div class="message-show2">

                    <div class="content">
                        <div class="box2">
                            <h3 class="text">俊 </h3>
                            <button class="add">添加</button>
                        </div>
                    </div>

                </div>

            </div>
            <!-- 初始ye -->
            <div class="right hide">
                <button class="close"> X </button>
                <br>
                <div class="beg">
                    <img src="./img/对话.png" alt="">
                </div>
            </div>
        </div>

        <!-- 弹窗 -->
        <div class="overlay" id="add">
            <div class="modal">
                <span class="close-button" onclick="closeModal()">&times;</span>
                <h2>申请理由</h2>
                <input type="text" id="inputField" placeholder="一句话,不要太长">
                <button id="apply">申请</button>
            </div>
        </div>
        <div class="overlay" id="more">
            <div class="modal">
                <span class="close-button" onclick="closeModal()">&times;</span>
                <button onclick="Delete_chat_history()">删除聊天记录</button>
                <button onclick="Delete_friend()">删除好友</button>
            </div>
        </div>

        <!-- 引入jquery -->
        <script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
        <script src="./js/common.js"></script>


        <!--[if gt IE 8]><!-->
        <script src="lib/script/highlight.pack.js"></script>
        <script>hljs.initHighlightingOnLoad();</script> <!--<![endif]-->
        <script src="lib/script/jquery.mousewheel-3.0.6.min.js"></script>
        <script src="lib/script/jquery.mCustomScrollbar.min.js"></script>
        <script src="src/js/jquery.emoji.js"></script>

        <script>

            emo();      

            var messageInputDiv = document.querySelector('#messageInput');
            // 为document添加keydown事件监听器，而不是直接给按钮添加  
            messageInputDiv.addEventListener('keydown', function (event) {
                // 检查是否按下了回车键（keyCode为13，或者使用event.key === 'Enter'）  
                if (event.key === 'Enter' || event.keyCode === 13) {
                    // 阻止默认的回车行为（在可编辑div中插入新行）  
                    event.preventDefault();
                    
                    // 在这里，您可以模拟按钮点击，或者执行您想要的任何操作  
                    simulateButtonClick(); // 调用模拟按钮点击的函数  
                    
                }
            });
            

            function simulateButtonClick() {
                // 这里是模拟按钮点击时要执行的代码  
                console.log('回车键被按下，模拟按钮点击');
                // ... 其他逻辑 ...  
                // 1.获取到发送按钮和消息输入框

                let messageInput = document.getElementById('messageInput').innerHTML;
                // a)先对输入框内容进行判定,如果为空,啥也不干
                if (messageInput == null || messageInput == "") {
                    // value 是null 或者''都会处罚这个条件
                    alert("输入为空");
                    return;
                }
                // b)还要获取当前选中的li标签的sessionId
                let selectedLi = document.querySelector('#session-list .selected');
                // 判断是否为空
                if (selectedLi == null) {
                    // 当前没有标签被选中
                    alert("没有标签被选中");
                    return;
                }
                let sessionId = selectedLi.getAttribute('message-session-id');
                var user_token = localStorage.getItem("user_token_header");
                // c)构造 json 数据 
                let req = {
                    type: 'WebSocketmessage',
                    sessionId: sessionId,
                    content: messageInput
                }

                // d)通过 websocket 发送消息
                // 此处要手动把 obeject 类型转换成String 类型json数据
                // 之前是jQuery ajax 帮转了,此时脱离jQuery
                req = JSON.stringify(req);
                console.log("[websocket] send: " + req);
                websocket.send(req);
                // e)清空输入框
                $('#messageInput').html("");
            }






            function Delete_friend() {
                // 会话Id
                let selectedLi = document.querySelector('#session-list .selected');
                let sessionId = selectedLi.getAttribute('message-session-id');
                $.ajax({
                    type: 'get',
                    url: '/deleteFriend?sessionId=' + sessionId,
                    success: function (result) {
                        if (result.status == 200) {
                            alert("删除好友成功");
                            location.assign("client.html");
                        } else {
                            alert("删除好友失败");
                        }
                    }
                });
            }
            function Delete_chat_history() {
                // 会话Id
                let selectedLi = document.querySelector('#session-list .selected');
                let sessionId = selectedLi.getAttribute('message-session-id');
                $.ajax({
                    type: 'get',
                    url: '/deleteMessage?sessionId=' + sessionId,
                    success: function (result) {
                        if (result.status == 200) {
                            alert("删除记录成功");
                            location.assign("client.html");
                        } else {
                            alert("删除记录失败");
                        }
                    }
                });
            }
            //上传图片
            function showFileUploadPopup() {
                document.getElementById("fileUploadPopup").style.display = "block";
            }

            function closeFileUploadPopup() {
                document.getElementById("fileUploadPopup").style.display = "none";
            }

            function submitFile(event) {
                //event.preventDefault(); // 阻止表单默认提交行为  
                // 这里可以添加文件上传的JavaScript代码  
                //event.preventDefault(); // 阻止表单默认提交行为  
                // 这里可以添加文件上传的JavaScript代码  
                alert('文件成功上传!');
                closeFileUploadPopup(); // 提交后关闭弹窗  
            }
            upload();
            function upload() {
                $(".upload").load(function () {
                    var form = document.getElementById('myForm');
                    var str = $(".upload").contents().text();

                    // 收到服务器给的url
                    let selectedLi = document.querySelector('#session-list .selected');
                    let sessionId = selectedLi.getAttribute('message-session-id');

                    // c)构造 json 数据 
                    let req = {
                        type: 'WebSocketmessage',
                        sessionId: sessionId,
                        content: str
                    }

                    // d)通过 websocket 发送消息
                    // 此处要手动把 obeject 类型转换成String 类型json数据
                    // 之前是jQuery ajax 帮转了,此时脱离jQuery
                    req = JSON.stringify(req);
                    console.log("[websocket] send: " + req);
                    websocket.send(req);
                    form.reset();
                });
            }

            ///////////////////////////////////////////////////////////
            // 个人信息展示/////////////////////////////////////////////
            //判断是否登录////////////////////////////////////////////
            function getUserInfo() {
                // var form = document.getElementById('myForm');
                // form.reset();
                $.ajax({
                    type: 'get',
                    url: '/userInfo',
                    success: function (body) {
                        if (body.status == 200) {
                            let userDiv = document.querySelector('.user');
                            userDiv.innerHTML = body.data.userName;
                            userDiv.setAttribute('user-id', body.data.userId);
                        } else {
                            alert("请您登陆后操作");
                             location.assign("login.html");

                            return;
                        }
                    },
                    error: function () {
                        alert("请您登陆后操作");
                        //location.assign("login.html")
                    }
                });
            }
            getUserInfo();
            //////////////////////////////////////////////
            // 操作 WebSocket/////////////////////////////
            //////////////////////////////////////////////

            // 测试
            function setCookie(name, value, days = 7) {
                var date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                var expires = "; expires=" + date.toUTCString();
                // 你可以添加其他属性，如SameSite和Secure  
                // var sameSite = "; SameSite=strict"; // 或者 "Lax"  
                // var secure = "; Secure"; // 仅在HTTPS下使用  
                document.cookie = name + "=" + (value || "") + expires + "; path=/";
            }
            var user_token = localStorage.getItem("user_token_header");
            // 使用示例  
            setCookie('token', user_token);

            // 创建websocket实例
            let websocket = new WebSocket("ws://"+location.host+"/WebSocketMessage ");
            //websocket.session.setAttribute("token",user_token);



            websocket.onopen = function () {
                console.log("websocket 链接成功");
            }
            websocket.onmessage = function (e) {
                console.log("websocket 收到消息 " + e.data);
                // TODO 后续实现的主要方法,展示界面上 

                // 此时收到的是字符串----json
                let resp = JSON.parse(e.data);
                if (resp.type == 'WebSocketmessage') {

                    // 处理消息响应
                    console.log(resp);
                    handleMessage(resp);
                } else if (resp.type == 'SuccessAdd') {
                    // 处理用户同意别人
                    let friendList = document.querySelector('#friend-list');
                    let li = document.createElement('li');
                    li.innerHTML = '<h4>' + resp.fromName + '</h4>';
                    friendList.appendChild(li);
                    handleMessage(resp);

                } else if (resp.type == 'FriendApply') {
                    // 处理别人加你
                    console.log("有人对你发出好友申请")
                    // 好友申请标签变成红色的
                    let messageShowDiv = document.querySelector('.message-show3');
                    let tabFind = document.querySelector('.tab .tab-find-friend');
                    tabFind.style.backgroundImage = 'url(img/好友申请3.png)'
                    addFriendApplyMessage(messageShowDiv, resp);
                }
            }

            function handleMessage(resp) {
                console.log("执行handleMessage函数");
                // 主要任务  1.显示到右侧列表(会话被选中)   2.显示到左侧会话标签页预览部分

                // 1.先根据响应中的sessionId 获取到当前会话的li标签(li标签属性)
                //    注意: 也可能不存在,之前没有会话,那就需要创建一个会话
                let curSessionLi = findSessionLi(resp.sessionId);
                if (curSessionLi == null) {
                    console.log("当前会话为空");
                    // 创造新的标签
                    curSessionLi = document.createElement('li');
                    curSessionLi.setAttribute('message-session-id', resp.sessionId);
                    curSessionLi.innerHTML = '<h3>' + resp.fromName + '</h3>'
                        + '<p>' + resp.content + '</p>';//先置空
                    console.log("resp.content = " + resp.content);
                    curSessionLi.onclick = function () {
                        clickSession(curSessionLi);
                    }
                }
                // 2.把新的消息显示到预览区,li标签中的p标签中(截断)
                let p = curSessionLi.querySelector('p');
                p.innerHTML = resp.content;
                if (p.innerHTML.length > 10) {
                    p.innerHTML = p.innerHTML.substring(0, 10) + '...';
                }
                // 3.把收到消息的会话,放到会话列表最上面
                let sessionListUL = document.querySelector('#session-list');
                sessionListUL.insertBefore(curSessionLi, sessionListUL.children[0]);
                // 4.如果当收到消息的会话处于被选中的状态,那就把当前的消息放到右侧的消息列表中
                //   调正滚动条,让用户直接看到
                if (curSessionLi.className == 'selected') {
                    // 写过这个函数
                    let messageShowDiv = document.querySelector('.right .message-show');
                    //截断
                    try {
                        new URL(resp.content);
                        //resp.content = resp.content.substring(0, resp.content.length );
                    } catch (err) {
                        addMessage(messageShowDiv, resp);
                        messageShowDiv.scrollTop = messageShowDiv.scrollHeight;
                        return;
                    }
                    console.log("添加信息 resp =" + resp);

                    addMessage(messageShowDiv, resp);
                    // 滚动条到最下方
                    messageShowDiv.scrollTop = messageShowDiv.scrollHeight;

                }

                // △可以在会话窗口,几次未读,提示音

            }
            function findSessionLi(targetSessionId) {
                let sessionLis = document.querySelectorAll('#session-list li');
                for (let li of sessionLis) {
                    let selectedId = li.getAttribute('message-session-id');
                    if (selectedId == targetSessionId) {
                        return li;
                    }
                }
                // 俩人还没有说过话,第一次接收到对方的消息
                return null;
            }
            websocket.onclose = function () {
                console.log("websocket 链接关闭");
            }
            websocket.onerror = function () {
                console.log("websocket 链接异常");
            }

            ///////////////////////////////////////////
            // 实现消息发送接收逻辑/////////////////////
            //////////////////////////////////////////





            function initSendButton() {
                // 1.获取到发送按钮和消息输入框
                let sendButton = document.getElementById('send');

                // 2.给发送按钮注册一个点击事件
                sendButton.onclick = function () {
                    var form = document.getElementById('myForm');


                    // 如果没有文件被选择，可以给出提示或进行其他处理  
                    let messageInput = document.getElementById('messageInput').innerHTML;
                    // a)先对输入框内容进行判定,如果为空,啥也不干
                    if (messageInput == null || messageInput == "") {
                        // value 是null 或者''都会处罚这个条件
                        alert("输入为空");
                        return;
                    }

                    console.log(messageInput);
                    // b)还要获取当前选中的li标签的sessionId
                    let selectedLi = document.querySelector('#session-list .selected');
                    // 判断是否为空
                    if (selectedLi == null) {
                        // 当前没有标签被选中
                        alert("没有标签被选中");
                        return;
                    }
                    let sessionId = selectedLi.getAttribute('message-session-id');
                    var user_token = localStorage.getItem("user_token_header");
                    // c)构造 json 数据 
                    let req = {
                        type: 'WebSocketmessage',
                        sessionId: sessionId,
                        content: messageInput
                    }

                    // d)通过 websocket 发送消息
                    // 此处要手动把 obeject 类型转换成String 类型json数据
                    // 之前是jQuery ajax 帮转了,此时脱离jQuery
                    req = JSON.stringify(req);
                    console.log("[websocket] send: " + req);
                    websocket.send(req);


                    // e)清空输入框
                    $('#messageInput').html("");

                }
            }
            initSendButton();

            // 会话列表的构建
            function getSessionList() {
                $.ajax({
                    type: 'get',
                    url: '/sessionList',
                    success: function (result) {

                        if (result.status == 200) {
                            let body = result.data;
                            let sessionList = document.querySelector('#session-list');
                            sessionList.innerHTML = '';

                            for (let session of body) {
                                if (session.lastMessage != '' && session.lastMessage.length > 10) {
                                    // 如果消息太⻓了, 就在预览窗⼝中截断.
                                    session.lastMessage = session.lastMessage.substring(0, 10);
                                }

                                let li = document.createElement('li');
                                // 通过⾃定义属性, 保存必要的信息. 以备后⾯使⽤.
                                li.setAttribute('message-session-id', session.sessionId);
                                li.innerHTML = '<h3>' + session.friends[0].friendName + '</h3>'
                                    + '<p>' + (session.lastMessage || '') + '</p>';
                                sessionList.appendChild(li);
                                // 增加点击事件的处理.
                                li.onclick = function () {
                                    clickSession(li);
                                }
                            }
                        } else {
                            alert('获取会话列表失败!');
                        }

                    },
                    error: function () {

                    }
                })
            }
            getSessionList();

            function clickSession(currentSessionLi) {
                let sessionLis = document.querySelectorAll('#session-list>li');
                // 把当前的会话设为⾼亮状态.
                activeSession(sessionLis, currentSessionLi);
                // 从服务器这⾥拉取到该会话的历史数据.
                let sessionId = currentSessionLi.getAttribute('message-session-id');
                getHistoryMessage(sessionId);
            }
            // 负责把多个 sessionLi 其中的指定元素设为⾼亮状态.
            // 这个⾼亮状态是 "互斥的", 只有⼀个元素能够获得
            function activeSession(sessionLis, activeSessionLi) {
                for (let sessionLi of sessionLis) {
                    if (sessionLi == activeSessionLi) {
                        sessionLi.className = 'selected';
                        let rights = document.querySelectorAll('.right');
                        rights[0].classList = 'right';
                        rights[1].classList = 'right hide';
                        rights[2].classList = 'right hide';
                        rights[3].classList = 'right hide';
                    } else {
                        sessionLi.className = '';
                    }
                }
            }
            function getHistoryMessage(sessionId) {
                console.log('获取历史消息: ' + sessionId);
                let titleDiv = document.querySelector('.right>.title>p');
                let messageShowDiv = document.querySelector('.message-show');
                // 清空已有内容
                titleDiv.innerHTML = '';
                messageShowDiv.innerHTML = '';
                // 设置会话的标题, 其实就是把当前选中的会话的 h3 标签内容设置进去.
                let selectedH3 = document.querySelector('#session-list>.selected>h3');
                if (selectedH3) {
                    titleDiv.innerHTML = selectedH3.innerHTML.trim()
                }
                if (!sessionId) {
                    // 新的会话没有 sessionId, 则不会获取历史数据.
                    return;
                }
                $.ajax({
                    type: 'get',
                    url: '/message?sessionId=' + sessionId,
                    success: function (result) {
                        if (result.status == 200) {

                            let body = result.data;
                            // 获取到当前⽤⼾的⽤⼾名
                            // 注意, 此处得到的 selfUsername 如果不 trim, 可能带有很多的换⾏符, 空格之
                            for (let message of body) {
                                addMessage(messageShowDiv, message);
                            }
                            messageShowDiv.scrollTop = messageShowDiv.scrollHeight

                        } else {
                            alert('获取历史消息失败!');
                        }

                    },
                    error: function () {

                    }
                });
            }
            function addMessage(messageShowDiv, message) {
                let selfUsername = document.querySelector('.user').innerHTML.trim();
                let messageDiv = document.createElement('div');
                let time = message.postTime;
                if (time == null) {
                    time = new Date().toLocaleString();

                }
                if (message.fromName != selfUsername) {
                    messageDiv.className = 'message message-left';
                    // 如果消息是别⼈发给⾃⼰的, 就放在左边
                    try {
                        new URL(message.content);
                        messageDiv.innerHTML = '<div class="box">'
                            + '<h4>' + message.fromName + '  ' + time + '</h4>'
                            + '<img style="width:200px;height:200px" src="' + message.content + '" />'
                            + '</div>';
                    } catch (err) {
                        //文本
                        messageDiv.innerHTML = '<div class="box">'
                            + '<h4>' + message.fromName + '  ' + time + '</h4>'
                            + '<p>' + message.content + '</p>'
                            + '</div>';
                    }
                } else {
                    // 如果消息是⾃⼰发给别⼈的, 就放在右边
                    messageDiv.className = 'message message-right';
                    try {
                        new URL(message.content);
                        messageDiv.innerHTML = '<div class="box">'
                            + '<h4>' + ' 我 ' + time + '</h4>'
                            + '<img style="width:200px;height:200px" src="' + message.content + '" />'
                            + '</div>';
                    } catch (err) {
                        //文本
                        messageDiv.innerHTML = '<div class="box">'
                            + '<h4>' + ' 我 ' + time + '</h4>'
                            + '<p>' + message.content + '</p>'
                            + '</div>';
                    }
                }

                messageShowDiv.appendChild(messageDiv);
                // 显示滚动条最底下
                //messageShowDiv.scrollTop = messageShowDiv.scrollHeight;
            }
            // 好友列表的构建
            function getFriendList() {
                $.ajax({
                    type: 'get',
                    url: '/friendList',
                    success: function (result) {
                        if (result.status == 200) {
                            let friendList = document.querySelector('#friend-list');
                            // 清空原有内容
                            friendList.innerHTML = '';
                            let body = result.data;
                            // 添加新内容
                            for (let friend of body) {
                                let li = document.createElement('li');
                                li.innerHTML = '<h4>' + friend.friendName + '</h4>';

                                // [新增代码] 增加点击事件的处理.
                                li.onclick = function () {
                                    clickFriend(friend);
                                }

                                friendList.appendChild(li);
                            }

                        } else {
                            alert('获取好友列表失败!');
                        }


                    },
                    error: function () {

                    }
                });
            }
            getFriendList();
            // 点击好友列表的标签
            function clickFriend(friend) {
                // 1. 在会话列表中, 查找当前是否存在某个会话和这个好友对应
                let sessionLi = findSessionByName(friend.friendName);
                let sessionList = document.querySelector('#session-list')
                if (sessionLi) {
                    // 2. 如果存在匹配的会话, 则直接把这个会话设为选中状态, 并移动到最前⾯
                    sessionList.insertBefore(sessionLi, sessionList.children[0])
                    // 点击⼀下新的会话, 触发⾼亮和拉取历史消息
                    sessionLi.click();
                } else {
                    // 3. 如果不存在匹配的会话, 则创建个新的会话, 并加⼊到会话列表最前⾯.
                    //并且通知服务器, 要创建会话了.
                    sessionLi = document.createElement('li');
                    sessionLi.innerHTML = '<h3>' + friend.friendName + '</h3>'
                        + '<p></p>';
                    sessionList.insertBefore(sessionLi, sessionList.children[0])
                    // 这个操作在实现 clickSession 的时候补充上. 保证新创建的 sessionLi 也能响应点
                    sessionLi.onclick = function () {
                        clickSession(sessionLi);
                    }
                    // 点击⼀下新的会话, 触发⾼亮和拉取历史消息
                    sessionLi.click();
                    // 4. 告诉服务器要新增⼀个会话
                    createSession(friend.friendId, sessionLi);
                }
                // 5. 同时切换标签⻚到会话列表
                //模拟⼀下⿏标点击.
                let tabSession = document.querySelector('.tab-session');
                tabSession.click();
            }
            //查找有没有这个会话
            function findSessionByName(name) {
                let sessions = document.querySelectorAll('#session-list>li');
                for (let li of sessions) {
                    let h3 = li.querySelector('h3');
                    if (name == h3.innerHTML) {
                        return li;
                    }
                }
                return null;
            }
            function createSession(friendId, sessionLi) {
                $.ajax({
                    type: 'post',
                    url: '/session?toUserId=' + friendId,
                    success: function (result) {

                        if (result.status == 200) {
                            let body = result.data;
                            console.log("创建会话成功! " + body.sessionId);
                            sessionLi.setAttribute('message-session-id', body.sessionId);
                        } else {
                            alert("创建会话失败!");
                        }
                    },
                    error: function () {

                    }
                });
            }

            function emo() {
                console.log('渲染表情');
                $("#messageInput").emoji({
                     button: '#a',
                    showTab: true,
                    animation: 'fade',
                    position: 'topRight',
                    icons: [{
                        name: "贴吧表情",
                        path: "dist/img/tieba/",
                        maxNum: 50,
                        file: ".jpg",
                        placeholder: ":{alias}:",
                        alias: {
                            1: "hehe",
                            2: "haha",
                            3: "tushe",
                            4: "a",
                            5: "ku",
                            6: "lu",
                            7: "kaixin",
                            8: "han",
                            9: "lei",
                            10: "heixian",
                            11: "bishi",
                            12: "bugaoxing",
                            13: "zhenbang",
                            14: "qian",
                            15: "yiwen",
                            16: "yinxian",
                            17: "tu",
                            18: "yi",
                            19: "weiqu",
                            20: "huaxin",
                            21: "hu",
                            22: "xiaonian",
                            23: "neng",
                            24: "taikaixin",
                            25: "huaji",
                            26: "mianqiang",
                            27: "kuanghan",
                            28: "guai",
                            29: "shuijiao",
                            30: "jinku",
                            31: "shengqi",
                            32: "jinya",
                            33: "pen",
                            34: "aixin",
                            35: "xinsui",
                            36: "meigui",
                            37: "liwu",
                            38: "caihong",
                            39: "xxyl",
                            40: "taiyang",
                            41: "qianbi",
                            42: "dnegpao",
                            43: "chabei",
                            44: "dangao",
                            45: "yinyue",
                            46: "haha2",
                            47: "shenli",
                            48: "damuzhi",
                            49: "ruo",
                            50: "OK"
                        },
                        title: {
                            1: "呵呵",
                            2: "哈哈",
                            3: "吐舌",
                            4: "啊",
                            5: "酷",
                            6: "怒",
                            7: "开心",
                            8: "汗",
                            9: "泪",
                            10: "黑线",
                            11: "鄙视",
                            12: "不高兴",
                            13: "真棒",
                            14: "钱",
                            15: "疑问",
                            16: "阴脸",
                            17: "吐",
                            18: "咦",
                            19: "委屈",
                            20: "花心",
                            21: "呼~",
                            22: "笑脸",
                            23: "冷",
                            24: "太开心",
                            25: "滑稽",
                            26: "勉强",
                            27: "狂汗",
                            28: "乖",
                            29: "睡觉",
                            30: "惊哭",
                            31: "生气",
                            32: "惊讶",
                            33: "喷",
                            34: "爱心",
                            35: "心碎",
                            36: "玫瑰",
                            37: "礼物",
                            38: "彩虹",
                            39: "星星月亮",
                            40: "太阳",
                            41: "钱币",
                            42: "灯泡",
                            43: "茶杯",
                            44: "蛋糕",
                            45: "音乐",
                            46: "haha",
                            47: "胜利",
                            48: "大拇指",
                            49: "弱",
                            50: "OK"
                        }
                    }, {
                        name: "QQ高清",
                        path: "dist/img/qq/",
                        maxNum: 91,
                        excludeNums: [41, 45, 54],
                        file: ".gif",
                        placeholder: "#qq_{alias}#"
                    }, {
                        name: "emoji高清",
                        path: "dist/img/emoji/",
                        maxNum: 84,
                        file: ".png",
                        placeholder: "#emoji_{alias}#"
                    }]
                });
                console.log('渲染表情完成');
            }
            
       

            function moreFuc() {
                document.querySelector('#more').style.display = 'block';
            }
            function openModal(receiverId) {
                console.log("receiverId - " + receiverId);
                document.querySelector('#add').style.display = 'block';

                let button = document.getElementById('apply');
                button.onclick = function () {
                    var reason = document.getElementById('inputField').value;

                    $.ajax({
                        type: 'get',
                        url: '/addFriendApply?receiverId=' + receiverId + '&reason=' + reason,
                        success: function (result) {
                            if (result.status == 200) {
                                alert("申请添加好友成功");

                            } else {
                                alert("申请添加好友失败");
                            }
                        }
                    });
                    closeModal();
                }
            }
            function closeModal() {
                let overlay = document.querySelectorAll('.overlay');
                overlay[0].style.display = 'none';
                overlay[1].style.display = 'none';
                overlay[2].style.display = 'none';
            }
            function search() {
                let Button = document.querySelector('.search .but');
                Button.onclick = function () {
                    // 拿到输入框里的内容 
                    let inputDiv = document.querySelector('.left .search input');
                    let userName = inputDiv.value;
                    inputDiv.innerHTML = '';
                    $.ajax({
                        type: 'get',
                        url: '/findFriend?toUserName=' + userName,
                        success: function (result) {
                            var data = result.data;
                            if (result.status == 200) {

                                let rights = document.querySelectorAll('.right');

                                let messageShowDiv = document.querySelector('.message-show2');
                                messageShowDiv.innerHTML = '';
                                for (var i = 0; i < data.length; i++) {
                                    addUserListMessage(messageShowDiv, data[i]);
                                }
                                rights[0].classList = 'right hide';
                                rights[1].classList = 'right hide';
                                rights[2].classList = 'right';
                                rights[3].classList = 'right hide';

                            } else {
                                alert("查询目标用户失败");
                            }
                        }
                    });
                }
                let addButtons = document.querySelectorAll('.add');
                for (let index = 0; index < addButtons.length; index++) {
                    addButtons[index].onclick = function () {
                        addButtons[i].style.display = 'block';
                    }
                }
            }
            search();

            function addUserListMessage(messageShowDiv, data) {
                let div = document.createElement('div');
                div.innerHTML =
                    '<div class="content">' +
                    '<div class="box2">'
                    + '<h3 class="text">' + data.userName + '</h3>'
                    + '<button class="add" data-receiver-id="' + data.userId + '">添加</button>'
                    + '</div>'
                    + '</div>';

                div.querySelectorAll('.add').forEach(function (button) {
                    button.addEventListener('click', function () {
                        // 使用getAttribute获取data-receiver-id的值  
                        var receiverId = this.getAttribute('data-receiver-id');
                        openModal(receiverId);
                        // 调用函数并传递receiver
                    });
                });
                messageShowDiv.appendChild(div);
            }
            function close() {
                let closeButtons = document.querySelectorAll('.right .close');

                for (let index = 0; index < closeButtons.length; index++) {
                    closeButtons[index].onclick = function () {
                        location.assign("begin.html")
                    }
                }
            }
            close();

            function initSwitchTab() {

                // 1.获取所需的元素(两个按钮,和两个列表)
                let tabSession = document.querySelector('.tab .tab-session');
                let tabFriend = document.querySelector('.tab .tab-friend');
                let tabFind = document.querySelector('.tab .tab-find-friend');
                let li = document.querySelector('.left .list .selected');

                // querySelectorAll可以全部取出
                // [0] 会话列表
                // [1] 好友列表
                // [2]
                let lists = document.querySelectorAll('.list');
                let rights = document.querySelectorAll('.right');
                // 2.点击不同按钮,设置背景状态
                //   同时展示不同列表,不展示的列表则隐藏
                tabSession.onclick = function () {
                    // a) 设置对话图标为-选中,好友图标未选中
                    tabSession.style.backgroundImage = 'url(img/会话.png)';
                    tabFriend.style.backgroundImage = 'url(img/好友1.png)';
                    tabFind.style.backgroundImage = 'url(img/好友申请.png)';
                    // b) 让会话列表展示,好友隐藏
                    lists[0].classList = 'list';
                    lists[1].classList = 'list hide';
                    lists[2].classList = 'list hide';
                    if (lists != null) {
                        //alert("111");
                        // rights[0].classList = 'right ';
                        // rights[1].classList = 'right hide';
                        // rights[2].classList = 'right hide';
                        // rights[3].classList = 'right hide';
                    }
                }
                tabFriend.onclick = function () {
                    //a) 设置对话图标为->选中,好友图标未选中
                    tabSession.style.backgroundImage = 'url(img/会话1.png)';
                    tabFriend.style.backgroundImage = 'url(img/好友.png)';
                    tabFind.style.backgroundImage = 'url(img/好友申请.png)';
                    // b) 让会话列表不展示,好友不隐藏
                    lists[1].classList = 'list';
                    lists[0].classList = 'list hide';
                    lists[2].classList = 'list hide';
                    // rights[0].classList = 'right hide ';
                    // rights[1].classList = 'right ';
                    // rights[2].classList = 'right hide';
                }
                tabFind.onclick = function () {
                    //a) 设置对话图标为->选中,好友图标未选中
                    tabSession.style.backgroundImage = 'url(img/会话1.png)';
                    tabFriend.style.backgroundImage = 'url(img/好友1.png)';
                    tabFind.style.backgroundImage = 'url(img/好友申请2.png)';
                    //加载好友申请的列表
                    $.ajax({
                        type: 'get',
                        url: '/getFriendApplyList',
                        success: function (result) {
                            var data = result.data;
                            if (result.status == 200) {
                                let messageShowDiv = document.querySelector('.message-show3');
                                messageShowDiv.innerHTML = '';
                                for (var i = 0; i < data.length; i++) {
                                    addFriendApplyMessage(messageShowDiv, data[i]);
                                }
                                // b) 让会话列表不展示,好友不隐藏
                                lists[1].classList = 'list hide';
                                lists[0].classList = 'list hide';
                                lists[2].classList = 'list';
                                rights[0].classList = 'right hide';
                                rights[1].classList = 'right';
                                rights[2].classList = 'right hide';
                                rights[3].classList = 'right hide';
                            } else {
                                alert("获取好友申请信息失败");
                            }
                        }
                    });
                }
            }
            initSwitchTab();
            function addFriendApplyMessage(messageShowDiv, data) {
                let tabFind = document.querySelector('.tab .tab-find-friend');
                tabFind.style.backgroundImage = 'url(img/好友申请3.png)'
                let div = document.createElement('div');
                div.innerHTML =
                    '<div class="content">'
                    + '<div class="box2">'
                    + '<h3 class="text">' + data.senderName + '</h3>'
                    + '<p>申请理由:</p>'
                    + '<p class="text">' + data.reason
                    + '</p>'
                    + '<button class="agree" data-sender-id="' + data.senderId + '">同意</button>'
                    + '<button class="disagree" data-sender-id="' + data.senderId + '">拒绝</button>'
                    + '</div>'
                    + '</div>';
                div.querySelectorAll('.agree').forEach(function (button) {
                    button.addEventListener('click', function () {
                        // 使用getAttribute获取data-sender-id的值  
                        var senderId = this.getAttribute('data-sender-id');
                        agree(senderId); // 调用函数并传递senderId  
                    });
                });
                div.querySelectorAll('.disagree').forEach(function (button) {
                    button.addEventListener('click', function () {
                        // 使用getAttribute获取data-sender-id的值  
                        var senderId = this.getAttribute('data-sender-id');
                        disagree(senderId); // 调用函数并传递senderId  
                    });
                });
                messageShowDiv.appendChild(div);
            }


            function agree(senderId) {
                //置空
                let div = document.querySelector('.message-show3');
                div.innerHTML = '';
                // 处理 senderId  

                $.ajax({
                    type: 'get',
                    url: '/addFriend?senderId=' + senderId,
                    success: function (result) {
                        if (result.status == 200) {
                            alert("添加好友成功");
                            //location.assign("client.html");
                            let rights = document.querySelectorAll('.right');
                            // rights[0].classList = 'right hide';
                            // rights[1].classList = 'right hide';
                            // rights[2].classList = 'right';
                            // rights[3].classList = 'right hide';
                            let tabFind = document.querySelector('.tab .tab-find-friend');
                            tabFind.click();
                        } else {
                            alert("添加好友失败");
                        }
                    }
                });
            }

            function disagree(senderId) {
                $.ajax({
                    type: 'get',
                    url: '/refuseAddFriend?senderId=' + senderId,
                    success: function (result) {
                        if (result.status == 200) {
                            alert("操作成功");
                            location.assign("client.html");
                        } else {
                            alert("操作失败");
                        }
                    }
                });

            }
        </script>
</body>

</html>